from optparse import OptionParser
import logging
import glob
import os
import sys
import httplib2

def main():
    usage = "usage: %prog POST_URL [options] "
    parser = OptionParser(usage)

    parser.add_option("-s", "--src_dir", dest="src_dir", 
                      default="./atom_entries",
                      help="Path to atom entry files.")
    parser.add_option("-u", "--username", dest="username", 
                      help="Username for Atompub server")
    parser.add_option("-p", "--password", dest="password",
                      help="Password for Atompub server")
    parser.add_option("-l","--log",dest="log", default=None, help="Defaults to\
STDOUT")
    parser.add_option("-d","--debug", dest="debug", action='store_true', default=False)
    (options, args) = parser.parse_args()

    if len(args) < 1:
        parser.error('The POST_URL is mandatory.')

    if options.log != None:
        logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(levelname)-8s %(message)s',
                    filename=options.log,
                    filemode='a+')
    else:
        logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(levelname)-8s %(message)s')

    if options.debug:
        httplib2.debuglevel=4
        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)

    headers={'Content-Type':'application/atom+xml;type=entry'}
    h = httplib2.Http(None)
    h.force_exception_to_status_code = True
    h.add_credentials(options.username, options.password)

    for atom_file in glob.glob(os.path.join(options.src_dir,'*.atom')):
        resp, content = h.request(args[0], "POST", body=open(atom_file).read(),
                                  headers=headers)
        if resp['status'] != '201':
            logging.error("Unexpected response status '%s' when posting\
                          %s."%(resp['status'],atom_file))
            continue 
        if not resp.has_key('location') or resp['location'] == '':
            logging.error("Empty response location when posting\
                          %s."%(atom_file))
            continue
        try:
            os.rename(atom_file,atom_file+'.posted')
        except OSError,e:
            logging.exception("Failed to rename '%s' to\
                              '%s'"%(atom_file,atom_file+'.posted'.Quitting))
            sys.exit(1)
        logging.info('Posted %s to %s'%(atom_file,resp['location']))
        logging.debug(resp)
        logging.debug(content)

if __name__ == "__main__":
    main()
